#include "gobang_network.h"

using namespace std;

Gobang_Network::Gobang_Network()
{
    log("start network thread");

    t = new tcp();

    this->start();
}

/*
 * 作用:告诉对方下棋的位置
 * @x:x坐标
 * @y:y坐标
 * @color:颜色数据-1，0，1
*/
uint8_t Gobang_Network::tellOpponent_chassxy(uint8_t x, uint8_t y, char color)
{
    uint8_t data[3];

    data[0] = x;
    data[1] = y;
    data[2] = (uint8_t)color;

    return tellOpponent_data(A_TELL_POS_XY, data, 3);
}

uint8_t Gobang_Network::tellOpponent_string(char *str, uint8_t len)
{
    return tellOpponent_data(A_TELL_STRING, (uint8_t *)str, len+1);
}

void Gobang_Network::tellOpponent_undo()
{
    tellOpponent_data(A_TELL_UNDO, NULL, 0);
}
uint8_t Gobang_Network::tellOpponent_color(char color)
{
    return tellOpponent_data(A_TELL_COLOR, (uint8_t *)&color, 1);
}

uint8_t Gobang_Network::tellOpponent_data(uint8_t fun, uint8_t *data, uint8_t datalen)
{
    qDebug()<<link_state<<tell_fd<<"\n";

    if (link_state == 0) {
        //qDebug()<<"link_state:"<<link_state;
        log("请先连接网络");
        return 0xff;
    }

    //log("zzfasong%d len:%d", tell_fd, datalen);
    t->tx(fun, tell_fd, data, datalen);

    return 0;
}

void Gobang_Network::tellOpponent_undo_state(uint8_t yes_no)
{
    tellOpponent_data(A_TELL_UNDORX, &yes_no, 1);
}

void Gobang_Network::run()
{

    for (int i=0;!QThread::currentThread()->isInterruptionRequested();i++) {

        if (i>=1800) {
            i=0;
            qDebug()<<"心跳线程";
            t->tx_uint8(A_POST_GET_HOUSE, 0);
        }
        msleep(100);
    }

    err("kill 心跳线程");
    QThread::currentThread()->exit(0);
}
